
import Vuex from 'vuex';
import Vue from 'vue';
Vue.use(Vuex);

/*读取本地购物车存储数据*/
var car=JSON.parse(localStorage.getItem('shpCar')||'[]');
/*应用程序数据共享, */
var store=new Vuex.Store({
    state:{
        /*存储购物车中的商品{id:0,count:1,price:1000,selected:true}*/
        shpCar:car
    },mutations:{
        addToCar(state,goods){
            /*点击添加到购物车,保存到state 的car上*/
            var flag=state.shpCar.some(item=>{
                if(item.id == goods.id){
                    item.count+=parseInt(goods.count);
                    return true;
                }
            });
            if(!flag){
                state.shpCar.push(goods);
            }
            /*将shpCar存储到本地存储*/
            localStorage.setItem('shpCar',JSON.stringify(state.shpCar));
        },
        updateGoodsInfo(state,goodsinfo){
            /*修改商品信息,修改商品的数量值*/
            state.shpCar.some(item=>{
                if(item.id==goodsinfo.id){
                    item.count=goodsinfo.count;
                    return true;
                }
            })
            /*将shpCar更新到本地存储*/
            localStorage.setItem('shpCar',JSON.stringify(state.shpCar));
        },
        remozeFormCar(state,id){
            /*根据id删除本地存储的数据*/
            state.shpCar.forEach((item,index)=>{
                if(item.id == id){
                    state.shpCar.splice(index,1);
                }
            });
            /*将shpCar更新到本地存储*/
            localStorage.setItem('shpCar',JSON.stringify(state.shpCar));
        },
        updateGoodsSelected(state,obj){
            /*更新商品选中的状态,obj:{id:87,selected:true}*/
            state.shpCar.forEach((item,index)=>{
                if(item.id == obj.id){
                    item.selected=obj.selected;
                }
            });
            /*将shpCar更新到本地存储*/
            localStorage.setItem('shpCar',JSON.stringify(state.shpCar));
        }
    },getters:{
        getAllCount(state){
            /*获取购物车数量,shpCar里面的每个对象的count属性值和*/
            var sum=0;
            state.shpCar.forEach(item=>{
                sum+=item.count
            });
            return sum;
        },
        getItemCount(state){
            /*返回id对应数量的数组对象,[{"3":6}]*/
            var o={};
            state.shpCar.forEach(item=>{
                o[item.id]=item.count;
            });
            return o;
        },
        getGoodsSelected(state){
            /*获取商品选中的姿态,返回: {id:selected}*/
            var o={};
            state.shpCar.forEach(item=>{
                o[item.id]=item.selected;
            });
            return o;
        },
        getGoodsCountAndAmount(state){
            var o={count:0,amount:0};
            state.shpCar.forEach(item=>{
                if(item.selected){
                    o.count+=item.count;
                    o.amount+=item.price*item.count;
                }
            });
            return o;
        }
    }
});

export default store;